from datetime import datetime
import uuid
from models.database import get_db_connection

class User:
    def __init__(self, user_id=None, username=None, password=None, email=None, 
                 avatar_url=None, role='user', created_at=None, last_login=None, status='active'):
        self.user_id = user_id or str(uuid.uuid4())
        self.username = username
        self.password = password
        self.email = email
        self.avatar_url = avatar_url
        self.role = role
        self.created_at = created_at or datetime.now()
        self.last_login = last_login
        self.status = status

    @staticmethod
    def find_by_username(username):
        """根据用户名查找用户"""
        conn = get_db_connection()
        if not conn:
            return None
            
        cursor = conn.cursor(dictionary=True)
        cursor.execute("SELECT * FROM user WHERE username = %s", (username,))
        user_data = cursor.fetchone()
        cursor.close()
        conn.close()
        
        if not user_data:
            return None
            
        return User(
            user_id=user_data['user_id'],
            username=user_data['username'],
            password=user_data['password'],
            email=user_data['email'],
            avatar_url=user_data['avatar_url'],
            role=user_data['role'],
            created_at=user_data['created_at'],
            last_login=user_data['last_login'],
            status=user_data['status']
        )
    
    def save(self):
        """保存用户到数据库"""
        conn = get_db_connection()
        if not conn:
            return False
            
        cursor = conn.cursor()
        try:
            cursor.execute(
                "INSERT INTO user (user_id, username, password, email, avatar_url, role, created_at, status) "
                "VALUES (%s, %s, %s, %s, %s, %s, %s, %s)",
                (self.user_id, self.username, self.password, self.email, 
                 self.avatar_url, self.role, self.created_at, self.status)
            )
            conn.commit()
            cursor.close()
            conn.close()
            return True
        except Exception as e:
            print(f"保存用户时出错: {str(e)}")
            conn.rollback()
            cursor.close()
            conn.close()
            return False